import { Ref } from 'vue';
import { defineStore } from 'pinia';
import { useLocalStorage } from '@vueuse/core';
import { User } from '@core/http/apis/user/user';

export const oathKey = 'oath';
type UserType = { name: string; avatar: string; id: string };

export type TOathStore = {
  userInfo: UserType;
};

export const defaultValue = {
  userInfo: {
    id: '',
    name: '',
    avatar: '',
  },
};

export const useOathStore = defineStore({
  id: 'oath',
  state: (): Ref<TOathStore> =>
    useLocalStorage(oathKey, {
      userInfo: defaultValue.userInfo,
    }),
  actions: {
    async setUserInfo() {
      const user = await new User().getUserInfo();
      this.$patch({ userInfo: user });
    },
    getLoginState() {
      return !!this.userInfo.name;
    },
    clear() {
      this.$patch({ userInfo: defaultValue.userInfo });
    },
  },
});

export type OathStoreType = ReturnType<typeof useOathStore>;
